<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  
  <style>
    table {
      border: 1px solid #eee;
      border-collapse: collapse;
    }

    th, td {
      border: 1px solid #eee;
      padding: 10px 15px;
      text-align: center;
    }

    th {
      background-color: #ccc;
    }
  </style>
</head>
<body>
  
  <div id="app"></div>
  
  <script src="../react-js/react.development.js" crossorigin></script>
  <script src="../react-js/react-dom.development.js" crossorigin></script>
  <script src="../react-js/babel.min.js"></script>
  
  <script src="./format_utils.js"></script>
  <script type="text/babel">
    class App extends React.Component {
      constructor() {
        super()

        this.state = {
          theadList: ['', '书籍名称', '出版日期', '价格', '购买数量', '操作'],
          booksList: [
            { id: 1, name: '<一千零一夜>', date: '2021-12-6', price: 80, count: 1 },
            { id: 5, name: '<老人与海>', date: '2021-12-7', price: 120, count: 1 },
            { id: 3, name: '<卖火柴的小女孩>', date: '2021-12-8', price: 99, count: 1 },
            { id: 4, name: '<木偶人>', date: '2021-12-9', price: 60, count: 1 },
            { id: 5, name: '<国王排名>', date: '2021-12-16', price: 299, count: 1 }
          ]
        }
      }

      renderBooks() {
        const { theadList, booksList } = this.state
        return (
          <div>
            <table>
              <thead>
                <tr>
                  { theadList.map(item => <th>{ item }</th> ) }
                </tr>  
              </thead>
              <tbody>
                {
                  booksList.map((item, index) => {
                    return (
                      <tr>
                        <td>{ index + 1 }</td>
                        <td>{ item.name }</td>
                        <td>{ item.date }</td>
                        <td>{ formatPrice(item.price)}</td>
                        <td>
                          <button
                            disabled={ item.count <= 1 } 
                            onClick={ () => this.changeBooksCount(index, -1) }
                          >
                            -
                          </button>
                          <span style={{margin: '0 6px'}}>{ item.count }</span> 
                          <button onClick={ () => this.changeBooksCount(index, 1) }>
                            +
                          </button>
                        </td>
                        <td>
                          <button onClick={ () => this.handlerDelete(index) }>
                            移除
                          </button>  
                        </td>
                      </tr>
                    )
                  })
                }  
              </tbody>
            </table>
            <h2>总价格：{ this.getTotalPrice() }</h2>
          </div>
        )
      }
      
      renderEmptyTip() {
        return <h2>购物车为空~</h2>
      }

      render() {
        // let { renderBooks, renderEmptyTip } = this
        return this.state.booksList.length ? this.renderBooks() : this.renderEmptyTip()
      }

      handlerDelete(index) {
        this.setState({
          // 这里违背了 react的设计原则 state中的数据的不可变性；
          // booksList: this.state.booksList.splice(index, 1)
          
          //filter是返回一个新的数组 并没有对state.booksList做修改
          booksList: this.state.booksList.filter((item, indey) => index != indey )
        })
      }

      getTotalPrice() {
        //1.遍历
        // let totalPrice = 0;
        // for(const item of this.state.booksList) {
        //   totalPrice += item.count * item.price
        // }
        // return formatPrice(totalPrice)

        //2.reduce （回调函数，初始值）
        //回调函数中第一个参数是：上一次回调函数的结果（第一次是没有上一次函数的回调函数结果，所以是初始值）
        const totalPrice = this.state.booksList.reduce((preVal, item, index, arr) => {
          return preVal + item.price * item.count
        }, 0)
        return formatPrice(totalPrice)
      }

      changeBooksCount(index, count) {
        //对state里的数据进行一个浅拷贝就就不违反state数据不可变的原则了
        const newBooks = [...this.state.booksList]
        newBooks[index].count += count
        this.setState({
          booksList: newBooks
        })
      }
    }

    ReactDOM.render(<App/>, document.getElementById('app'))
  </script>
  
</body>
</html>